<template>
  <div class="register-container">
    <el-form ref="registerForm" :model="registerForm" :rules="registerRules" class="register-form" label-width="0">
      <div class="title-container">
        <h3 class="title">用户注册</h3>
      </div>
      <el-form-item prop="username">
        <el-input v-model="registerForm.username" placeholder="请输入账号" prefix-icon="el-icon-user" />
      </el-form-item>
      <el-form-item prop="password">
        <el-input v-model="registerForm.password" placeholder="请输入密码" type="password" prefix-icon="el-icon-lock" show-password />
      </el-form-item>
      <el-form-item prop="confirmPassword">
        <el-input v-model="registerForm.confirmPassword" placeholder="请再次输入密码" type="password" prefix-icon="el-icon-lock" show-password />
      </el-form-item>
      <el-form-item prop="captcha">
        <el-input v-model="registerForm.captcha" placeholder="请输入验证码" prefix-icon="el-icon-key" />
        <div class="captcha-container">
          <img
            :src="captchaImage"
            alt="验证码"
            class="captcha-image"
            @click="generateCaptchaImage"
          >
        </div>
        <!-- <el-button class="captcha-container" @click="generateCaptcha">{{ captcha }}</el-button> -->
      </el-form-item>
      <el-button type="primary" class="register-button" @click="handleRegister">注册</el-button>
    </el-form>
  </div>
</template>

<script>
import { createUser, checkUsernameExists } from '@/api/user'

export default {
  data() {
    const validateUsername = async(rule, value, callback) => {
      if (!value) {
        return callback(new Error('账号不能为空'))
      }
      try {
        const response = await checkUsernameExists(value)
        if (response.exists) {
          callback(new Error('该账号已存在'))
        } else {
          callback()
        }
      } catch (error) {
        callback(new Error('验证账号时出错'))
      }
    }
    const validatePassword = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('密码不能为空'))
      }
      if (value.length < 6) {
        callback(new Error('密码不能少于6位'))
      } else {
        callback()
      }
    }
    const validateConfirmPassword = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请再次输入密码'))
      }
      if (value !== this.registerForm.password) {
        callback(new Error('两次输入的密码不一致'))
      } else {
        callback()
      }
    }
    const validateCaptcha = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('验证码不能为空'))
      }
      if (value !== this.captcha) {
        callback(new Error('验证码不正确'))
      } else {
        callback()
      }
    }
    return {
      registerForm: {
        username: '',
        password: '',
        confirmPassword: '',
        captcha: ''
      },
      registerRules: {
        username: [{ validator: validateUsername, trigger: 'blur' }],
        password: [{ validator: validatePassword, trigger: 'blur' }],
        confirmPassword: [{ validator: validateConfirmPassword, trigger: 'blur' }],
        captcha: [{ validator: validateCaptcha, trigger: 'blur' }]
      },
      captcha: '', // 验证码文本
      captchaImage: '' // 验证码图片的 base64 数据
      // captcha: this.generateCaptcha()
    }
  },
  mounted() {
    this.generateCaptchaImage() // 初始化生成验证码图片
  },
  methods: {
    // 生成验证码图片
    generateCaptchaImage() {
      const canvas = document.createElement('canvas')
      const ctx = canvas.getContext('2d')

      // 设置画布大小
      canvas.width = 120
      canvas.height = 40

      // 设置背景色
      ctx.fillStyle = '#f0f2f5'
      ctx.fillRect(0, 0, canvas.width, canvas.height)

      // 生成随机验证码
      const chars = '0123456789'
      let captcha = ''
      for (let i = 0; i < 4; i++) {
        captcha += chars.charAt(Math.floor(Math.random() * chars.length))
      }
      this.captcha = captcha

      // 绘制验证码文本
      ctx.font = '24px Arial'
      ctx.fillStyle = '#409eff'
      ctx.textAlign = 'center'
      ctx.textBaseline = 'middle'
      ctx.fillText(captcha, canvas.width / 2, canvas.height / 2)

      // 添加干扰线
      for (let i = 0; i < 5; i++) {
        ctx.strokeStyle = '#ccc'
        ctx.beginPath()
        ctx.moveTo(Math.random() * canvas.width, Math.random() * canvas.height)
        ctx.lineTo(Math.random() * canvas.width, Math.random() * canvas.height)
        ctx.stroke()
      }

      // 添加干扰点
      for (let i = 0; i < 50; i++) {
        ctx.fillStyle = '#999'
        ctx.beginPath()
        ctx.arc(
          Math.random() * canvas.width,
          Math.random() * canvas.height,
          1,
          0,
          2 * Math.PI
        )
        ctx.fill()
      }

      // 将画布内容转换为 base64 图片
      this.captchaImage = canvas.toDataURL('image/png')
    },
    generateCaptcha() {
      const chars = '0123456789'
      let captcha = ''
      for (let i = 0; i < 4; i++) {
        captcha += chars.charAt(Math.floor(Math.random() * chars.length))
      }
      this.captcha = captcha
      return captcha
    },
    async handleRegister() {
      this.$refs.registerForm.validate(async(valid) => {
        if (valid) {
          try {
            const response = await createUser({
              username: this.registerForm.username,
              password: this.registerForm.password
            })
            console.log('response:', response)
            if (response.code === 'success') {
              this.$message.success('注册成功')
              this.$router.push('/login')
            } else {
              this.$message.error(response.message || '注册失败')
            }
          } catch (error) {
            this.$message.error('注册失败，请检查输入信息')
          }
        }
      })
    }
  }
}
</script>

<style scoped>
.register-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f0f2f5;
}

.register-form {
  width: 400px;
  padding: 24px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.title-container {
  text-align: center;
  margin-bottom: 24px;
}

.title {
  font-size: 24px;
  color: #303133;
}

.captcha-button {
  margin-left: 10px;
  font-size: 14px;
  color: #409eff;
}

.register-button {
  width: 100%;
  margin-top: 20px;
}

.captcha-container {
  display: flex;
  align-items: center;
  margin-left: 10px;
}

.captcha-image {
  width: 120px;
  height: 40px;
  cursor: pointer;
  border: 1px solid #ddd;
  border-radius: 4px;
}
</style>
